from django.shortcuts import render, HttpResponse, redirect
from app01.myforms import MyRegForm
from app01 import models
from django.http import JsonResponse
from PIL import Image, ImageDraw, ImageFont
import random
from io import BytesIO, StringIO
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from app01.utils.paper import Pagination
from bs4 import BeautifulSoup
from django.db.models import Count
from django.db.models.functions import TruncMonth
# Create your views here.
def get_random():
    return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

def get_code(request):
    image_obj = Image.new('RGB', (430, 35), get_random())
    image_draw_obj = ImageDraw.Draw(image_obj)
    image_font_obj = ImageFont.truetype('static/font/111.ttf', 35)
    code = ''
    for i in range(5):
        random_upper = chr(random.randint(65, 90))
        random_lower = chr(random.randint(97, 122))
        random_int = str(random.randint(0, 9))
        tmp = random.choice([random_upper, random_lower, random_int])
        image_draw_obj.text((i*60+60,0), tmp, get_random(),image_font_obj)
        code += tmp
    print(code)
    request.session['code'] = code
    io_obj = BytesIO()
    image_obj.save(io_obj, 'png')
    return HttpResponse(io_obj.getvalue())

def register(request):
    form_obj = MyRegForm()
    if request.method == 'POST':
        back_dic = {'code': 1000, 'msg': ''}
        is_alive = MyRegForm(request.POST)
        if is_alive.is_valid():
            clean_data = is_alive.cleaned_data
            clean_data.pop('confirm_password')
            if request.FILES.get('avatar'):
                clean_data['avatar'] = request.FILES.get('avatar')
            models.UserInfo.objects.create_user(**clean_data)
            back_dic['url'] = '/login/'
        else:
            back_dic['code'] = 2000
            back_dic['msg'] = is_alive.errors
        return JsonResponse(back_dic)
    return render(request, 'register.html', locals())

def login(request):
    if request.method == 'POST':
        back_dic = {'code': 1000, 'msg': ''}
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('code')
        print(username, password, code)
        user_obj = auth.authenticate(request, username=username, password=password)
        print(user_obj)
        if user_obj:
            if code.upper() == request.session.get('code').upper():
                back_dic['url'] = '/home/'
                auth.login(request, user_obj)
            else:
                back_dic['code'] = 1001
                back_dic['msg'] = '验证码不正确'
        else:
            back_dic['code'] = 1002
            back_dic['msg'] = '账户或密码不正确'
        return JsonResponse(back_dic)
    return render(request, 'login.html')

def home(request):
    article_queryset = models.Article.objects.all()
    return render(request, 'home.html', locals())

@login_required
def set_password(request):
    if request.method == 'POST':
        back_dic = {'code': 1000, 'msg': ''}
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        is_alive = request.user.check_password(old_password)
        print(is_alive)
        if is_alive:
            if new_password == confirm_password:
                request.user.set_password(new_password)
                request.user.save()
            else:
                back_dic['code'] = 1001
                back_dic['msg'] = '两次密码不一致'
        else:
            back_dic['code'] = 1002
            back_dic['msg'] = '原密码输入不正确'
        return JsonResponse(back_dic)

@login_required
def logout(request):
    auth.logout(request)
    return redirect('/home/')

def site(request, username, **kwargs):
    user_obj = models.UserInfo.objects.filter(username=username).first()
    if not user_obj:
        return render(request, 'error.html', locals())
    blog = user_obj.blog
    article_list = models.Article.objects.filter(blog=blog).all()
    if kwargs:
        condition = kwargs.get('condition')
        param = kwargs.get('param')
        # 判断用户到底想按照哪个条件筛选数据
        if condition == 'category':
            article_list = article_list.filter(category_id=param)
        elif condition == 'tag':
            article_list = article_list.filter(tags__id=param)
        else:
            year, month = param.split('-')  # 2020-11  [2020,11]
            article_list = article_list.filter(create_time__year=year, create_time__month=month)
    # 当前用户所有分类及分类下的文章数
    # category_list = models.Category.objects.filter(blog=blog).annotate(count_num=Count('article')).values_list('name', 'count_num', 'pk')
    # # print(category_list)
    # # 当前用户所有标签及标签下的文章数
    # tag_list = models.Tag.objects.filter(blog=blog).annotate(count_num=Count('article')).values_list('name', 'count_num', 'pk')
    # # print(tag_list)
    # date_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values('month').annotate(count_num=Count('pk')).values_list('month','count_num')
    # print(date_list)
    return render(request, 'site.html', locals())

def article_detail(request, username, article_id):
    user_obj = models.UserInfo.objects.filter(username=username).first()
    blog = user_obj.blog
    article_obj = models.Article.objects.filter(pk=article_id, blog__userinfo__username=username).first()
    if not user_obj:
        return render(request, 'error.html')
    comment_list = models.Comment.objects.filter(article_id=article_id)
    return render(request, 'article_detail.html', locals())

from django.db.models import F
import json
def up_or_down(request):
    back_dic = {'code': 1000, 'msg': ''}
    if request.is_ajax():
        if request.method == 'POST':
            article_id = request.POST.get('article_id')
            is_up = request.POST.get('is_up')
            is_up = json.loads(is_up)

            if request.user.is_authenticated():
                article_obj = models.Article.objects.filter(pk=article_id).first()
                if not request.user.username == article_obj.blog.userinfo.username:
                    is_click = models.UpAndDown.objects.filter(user=request.user, article=article_obj).first()
                    if not is_click:
                        if is_up:
                            models.Article.objects.filter(pk=article_id).update(up_num=F('up_num') + 1)
                            back_dic['msg'] = '点赞成功'
                        else:
                            models.Article.objects.filter(pk=article_id).update(down_num=F('down_num') + 1)
                            back_dic['msg'] = '点踩成功'
                        models.UpAndDown.objects.create(user=request.user, article=article_obj, is_up=is_up)
                    else:
                        back_dic['code'] = 1001
                        back_dic['msg'] = '你已经点过了,不能再点了'  # 这里你可以做的更加的详细 提示用户到底点了赞还是点了踩
                else:
                    back_dic['code'] = 1002
                    back_dic['msg'] = '你个臭不要脸的!'
            else:
                back_dic['code'] = 1003
                back_dic['msg'] = '请先<a href="/login/">登陆</a>'
    return JsonResponse(back_dic)

def comment(request):
    back_dic = {'code': 1000, 'msg': ''}
    if request.is_ajax():
        print(666)
        if request.user.is_authenticated():
            article_id = request.POST.get('article_id')
            content = request.POST.get('content')
            parent_id = request.POST.get('parent_id')
            models.Article.objects.filter(pk=article_id).update(comment_num=F('comment_num') + 1)
            models.Comment.objects.create(user=request.user, article_id=article_id, content=content, parent_id=parent_id)
            back_dic['msg'] = '评论成功'
        else:
            back_dic['code'] = 1001
            back_dic['msg'] = '用户未登陆'
    return JsonResponse(back_dic)

@login_required
def backend(request):
    article_list = models.Article.objects.filter(blog=request.user.blog)
    page_obj = Pagination(current_page=request.GET.get('page', 1), all_count=article_list.count())
    page_queryset = article_list[page_obj.start:page_obj.end]
    return render(request, 'backend/backend.html', locals())

@login_required
def add_article(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        category = request.POST.get('category')
        tag = request.POST.getlist('tag')
        # 模块使用
        soup = BeautifulSoup(content, 'html.parser')
        # 获取所有标签
        tags = soup.find_all()
        for i in tags:
            # i.name 查看标签的名字
            if i.name == 'script':
                # 删除标签
                i.decompose()
        # 截取150个 ‘文本’
        # desc = content[0:150]
        desc = soup.text[0:150]
        article_obj = models.Article.objects.create(title=title, desc=desc, content=str(soup), category_id=category, blog=request.user.blog)
        article_obj_list = []
        for i in tag:
            article_obj_list.append(models.Article2Tag(article=article_obj, tag_id=i))
        models.Article2Tag.objects.bulk_create(article_obj_list)
        return redirect('/backend/')
    category_list = models.Category.objects.filter(blog=request.user.blog)
    tag_list = models.Tag.objects.filter(blog=request.user.blog)
    return render(request, 'backend/add_article.html', locals())

import os
from bbs_project import settings

def upload_image(request):
    '''
        返回格式(JSON)
            //成功时
        {
                "error" : 0,
                "url" : "http://www.example.com/path/to/file.ext"
        }
        //失败时
        {
                "error" : 1,
                "message" : "错误信息"
        }
    :param request:
    :return:
    '''
    back_dic = {'error': 0, }  # 先提前定义返回给编辑器的数据格式


    # django报错:django.core.exceptions.ImproperlyConfigured: 处理办法
    os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
    # 用户写文章上传的图片 也算静态资源 也应该防盗media文件夹下
    if request.method == "POST":
        # 获取用户上传的图片对象
        # print(request.FILES)  # 打印看到了健固定叫imgFile
        file_obj = request.FILES.get('imgFile')
        # 手动拼接存储文件的路径
        file_dir = os.path.join(settings.BASE_DIR, 'media', 'article_img')
        # 优化操作 先判断当前文件夹是否存在 不存在 自动创建
        if not os.path.isdir(file_dir):
            os.mkdir(file_dir)  # 创建一层目录结构  article_img
        # 拼接图片的完整路径
        file_path = os.path.join(file_dir, file_obj.name)
        with open(file_path, 'wb') as f:
            for line in file_obj:
                f.write(line)
        back_dic['url'] = '/media/article_img/%s' % file_obj.name

    return JsonResponse(back_dic)

def set_avatar(request):
    back_dic = {'code': 1000}
    if request.method == 'POST':
        file_obj = request.FILES.get('avatar')
        # models.UserInfo.objects.filter(pk=request.user.pk).update(avatar=file_obj)  # 不会再自动加avatar前缀
        # 1.自己手动加前缀
        # 2.换一种更新方式
        user_obj = request.user
        user_obj.avatar = file_obj
        user_obj.save()
        return redirect('/home/')
        back_dic['url'] = '/home/'
    return JsonResponse(back_dic)